package com.example.uupaymuch.controller.notice.wudi;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PayComponent {

//    private final String noticePay = "http://192.168.50.145:27003/api/pay/notify/brazilpay/wudipay";
        private final String noticePay = "http://localhost:27003/api/pay/notify/brazilpay/wudipay";
//    private final String noticePay = "https://pay-india.ssonicpay.com/api/pay/notify/brazilpay/wudipay";
    private static final String HMAC_SECRET = "123456789"; // 从安全配置中获取
    //    private final Random random = new Random();
//    private final double successProbability = 0.5; // 50% 的成功概率
    private final CloseableHttpClient httpClient;

    public PayComponent() {
        // 创建带有连接池的 HttpClient 实例
        this.httpClient = HttpClients.custom()
                .setMaxConnTotal(200)  // 设置最大连接数
                .setMaxConnPerRoute(200)  // 设置每个路由的最大连接数
                .build();
    }

    ScheduledThreadPoolExecutor scheduledThreadPoolExecutorTransfer =
            new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 2);
    private static final Map<String, Object> PARAMS;

    // 静态初始化块
    static {
        PARAMS = new HashMap<>();
        PARAMS.put("external_id", "b1681fe6931c4ff8a57c775d6fee4387");
        PARAMS.put("debtor_document_number", null);
        PARAMS.put("debtor_name", null);
        PARAMS.put("payer_request", null);
        PARAMS.put("additional_information", new Object[]{}); // 空数组
        PARAMS.put("qr_code", "00020101021226810014br.gov.bcb.pix2559api-h.fakebank.com.br/api/cob/b1681fe6931c4ff8a57c775d6fee43875204000053039865802BR5913SUPERPAGAMENTOS LTDA6009SAO PAULO62070503***630442F4");
        PARAMS.put("qr_code_image_url", "https://api-h.wudi-pay.codesign.ag/qr_code/WD1727231601932M1724118185RS75L");
        PARAMS.put("expires_at", "2024-09-25T02:46:09.000000Z");
        PARAMS.put("provider", "FAKE_BANK");
        PARAMS.put("provider_account", "1");
        PARAMS.put("fee", 0.01);
        PARAMS.put("account_id", 74);
        PARAMS.put("workspace_id", 34);
        PARAMS.put("updated_at", "2024-09-25T02:36:09.000000Z");
        PARAMS.put("created_at", "2024-09-25T02:36:09.000000Z");
        PARAMS.put("id", 130033);
    }

    public void doNotifyPay(String txid, String text, String amount) {
        scheduledThreadPoolExecutorTransfer.schedule(() -> {
            // 执行推送
            try {
                notifyPaymentPay(txid, text, amount);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }, 1, TimeUnit.SECONDS);
    }

    public void notifyPaymentPay(String payOrderId, String text, String amount) throws IOException {
        Map<String, Object> params = new HashMap<>(PARAMS); // 深拷贝
        params.put("txid", payOrderId);
        params.put("status", text);
        params.put("amount", amount);

        try {
            log.info("支付回调请求 body:{}, url:{}", params, noticePay);
            HttpPost request = new HttpPost(noticePay);
            String json = new ObjectMapper().writeValueAsString(params);
            StringEntity entity = new StringEntity(json);
            entity.setContentType("application/json");
            request.setEntity(entity);

            // 生成 HMAC SHA256 签名
            String hmacsha256Signature = generateHMACSHA256Signature(json, HMAC_SECRET);
            request.setHeader("Signature", hmacsha256Signature);

            CloseableHttpResponse response = httpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                log.error("Failed to notify payment. HTTP Status: {}", statusCode);
            }

        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            log.error("Error generating HMAC: {}", e.getMessage());
            throw new RuntimeException("Error generating HMAC", e);
        } catch (IOException e) {
            log.error("Error serializing JSON: {}", e.getMessage());
            throw e; // 重新抛出以便上层处理
        }
    }

    public static String generateHMACSHA256Signature(String data, String secret)
            throws NoSuchAlgorithmException, InvalidKeyException {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        mac.init(secretKeySpec);

        byte[] rawHmac = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));

        // 将字节数组转换为十六进制字符串
        StringBuilder sb = new StringBuilder(2 * rawHmac.length);
        for (byte b : rawHmac) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}
